/*
 * Created on 2005-3-22
 * Copyright: Bluejay Networks Inc. 2004
 *
 * This software is the proprietary information of Bluejay Networks Inc. & 
 * Inquiry Management Systems Ltd.  
 * Use is subject to license terms.
 * 
 */
package com.ims.iaa.AD;

import java.io.IOException;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import com.ims.iaa.IaaDebug;
import com.ims.iaa.IaaUtil;
import com.ims.iaa.URLUtil;

/**
 * @version 1.0
 * @author changsheng gong
 * @version 1.1 at 2005-03-31
 * @author ShengMengBai
 * 
 * analyze a href link
 */
public class HrefParser implements Serializable{
    private static final String MIME_TYPE_IMG = "image";
    private static final String MIME_TYPE_JPG = "image/jpeg";
    private static final String MIME_TYPE_GIF = "image/gif";
    private static final String MIME_TYPE_PNG = "image/png";
    private static final String MIME_TYPE_SWF = "application/x-shockwave-flash";
    private static final String MIME_TYPE_JAR = "application/java-archive";
    private static final String MIME_TYPE_ZIP = "application/zip";
	private static final int CONN_NEVER = 0;
	private static final int CONN_SUCCESSFUL = 1;
	private static final int CONN_FAILED = -1;
       
	private String m_sUserAgent;
	private URL m_objOriginalUrl;
	private URL m_objRedirectUrl;
	private AdAgency m_sObjAgency;
	private String m_sMimeType = "";
	private int m_iContentLen = 0;
	private URLConnection m_uc = null;
	private int m_iConnState = 0;

    public HrefParser(URL objTargetUrl, String sUserAgent){
        m_objOriginalUrl = objTargetUrl;
        m_objRedirectUrl = objTargetUrl;
        m_sUserAgent = sUserAgent;
     }
    
    public URL getOriginalURL() {
		return m_objOriginalUrl;
	}
    /**
     * @return
     * @exception RuntimeException if call it before call connect(); 
     */
    public URL getRedirectURL(){
        if(m_iConnState == CONN_NEVER){
            throw new RuntimeException("Must call connect() at first.");
        }
        return m_objRedirectUrl;
    }
    /**
     * @return
     * @exception RuntimeException if call it before call connect(); 
     */
    public AdAgency getAgency(){
       	return m_sObjAgency;
    }
    /**
     * get the URLConnection object
     * @return
     * @exception RuntimeException if call it before call connect(); 
     */
    public URLConnection getConnection(){
        if(m_iConnState == CONN_NEVER){
            throw new RuntimeException("Must call connect() at first.");
        }
       	return m_uc;
    }
    /**
     * Some mimetype is error, so after call connect(), 
     * you can call getMimeType() to get correct mimetype.
     * @return
     * @exception RuntimeException if call it before call connect(); 
     */
    public String getMimeType(){
        if(m_iConnState == CONN_NEVER){
            throw new RuntimeException("Must call connect() at first.");
        }
		if(m_sMimeType == null){
		    m_sMimeType = "";
		}
		resetMimeType();
        return m_sMimeType;
    }
    /**
      * @return
     * @exception RuntimeException if call it before call connect(); 
     */
    public int getContentLength(){
        if(m_iConnState == CONN_NEVER){
            throw new RuntimeException("Must call connect() at first.");
        }
        return m_iContentLen;
    }
    
    public boolean connect(){
        m_iConnState = CONN_SUCCESSFUL;
        boolean bRet = reconnect(m_objOriginalUrl);
        if(bRet){
			//we must get the content type, otherwise, we can not ge the real target.
			m_sMimeType = m_uc.getContentType();
			m_iContentLen = m_uc.getContentLength();
			//if(m_iContentLen < 0)
			//	m_iContentLen = 0;
			if(m_iContentLen == -1){
				m_iContentLen = IaaDebug.MaxImageSize-1;  //added by yxy 20080623
			}else if(m_iContentLen < 0){
			    m_iContentLen = IaaDebug.MaxImageSize-1;  //added by yxy 20080624
			}
			IaaDebug.end("connect target " + m_uc.getURL());
//++commented by changsheng 2006-6-30			
			/*m_objRedirectUrl = m_uc.getURL();*/
//--
        }
//++add by changsheng 2006-6-30
        m_objRedirectUrl = m_uc.getURL();
//--
        return bRet;
    }
    private boolean reconnect(URL url){
        try{
			//SimpleCookies m_objCookie = new SimpleCookies();
			
            m_uc = url.openConnection();
            m_uc.setRequestProperty("User-Agent", m_sUserAgent);
//++changsheng for persistent connection
            m_uc.setRequestProperty("Connection", "Keep-Alive");   
//--
			//m_objCookie.writeCookies( m_uc );
			IaaDebug.begin("connect target " + m_uc.getURL());
			m_uc.connect();
			int iResponseCode = ((HttpURLConnection)m_uc).getResponseCode();
			switch(iResponseCode){
				case HttpURLConnection.HTTP_OK:
				    break;
				case HttpURLConnection.HTTP_MOVED_TEMP:
				    String sURL = m_uc.getHeaderField("Location");
					if(sURL != null){
					    URL tmpURL = URLUtil.getURL(sURL);
					    m_objRedirectUrl = tmpURL;
					    return reconnect(tmpURL);
					}
				default:
			        m_iConnState = CONN_FAILED;
				    break;
			}
			IaaDebug.end("connect target " + m_uc.getURL());
	    } catch (IOException e) {
	        m_iConnState = CONN_FAILED;
			IaaUtil.log("It is failed to connect to URL: " + m_uc.getURL());
		}
	    return (m_iConnState == CONN_SUCCESSFUL);
    }
    public boolean isConnectSuccessful(){
        if(m_iConnState == CONN_NEVER){
            throw new RuntimeException("Must call connect() at first.");
        }
	    return (m_iConnState == CONN_SUCCESSFUL);
    }
    
    private void resetMimeType(){
        if((m_sMimeType.indexOf(MIME_TYPE_IMG) == -1) &&
            !MIME_TYPE_SWF.equals(m_sMimeType) &&
            !MIME_TYPE_JAR.equals(m_sMimeType) &&
            !MIME_TYPE_ZIP.equals(m_sMimeType)){
            String sExt = m_objRedirectUrl.getPath();
            if(sExt == null || sExt.length() < 5){
                return;
            }
            String sRight4 = sExt.substring(sExt.length() - 5).toLowerCase();
            String sRight3 = sRight4.substring(1);
            if(sRight4.charAt(0) == '.' || sRight3.charAt(0) == '.'){
	            if(sRight3.equals(".jpg") || sRight4.equals(".jpeg") || sRight3.equals(".jpe")){
	                m_sMimeType = MIME_TYPE_JPG;
	            }else if(sRight3.equals(".gif")){
	                m_sMimeType = MIME_TYPE_GIF;
	            }else if(sRight3.equals(".png")){
	                m_sMimeType = MIME_TYPE_PNG;
	            }else if(sRight3.equals(".swf")){
	                m_sMimeType = MIME_TYPE_SWF;
	            }else if(sRight3.equals(".jar")){
	                m_sMimeType = MIME_TYPE_JAR;
	            }else if(sRight3.equals(".zip")){
	                m_sMimeType = MIME_TYPE_ZIP;
	            }else if(sRight3.equals(".swf")){
	                m_sMimeType = MIME_TYPE_SWF;
	            }
	        }
        }
    }
    
    public boolean isAdAgency(List lstAgency)  {
		if (m_objOriginalUrl != null){
			if(lstAgency != null){
				int iCount = lstAgency.size();
				for(int iIndex = 0; iIndex < iCount; iIndex++){
					AdAgency objAgency = (AdAgency)lstAgency.get(iIndex);
					if (objAgency.IsRefering(m_objOriginalUrl)){
					    m_sObjAgency = objAgency;
						return true;
					}
				}
			}
		}
		return false;
	}
    public String toString(){
        if(m_iConnState == CONN_NEVER){
            return "Unconnect to: " + m_objOriginalUrl;
        }else{
            if(m_iConnState == CONN_SUCCESSFUL){
                return "It is successful to connect to: " + m_objOriginalUrl + "\t\r\n redirect to: " + m_objRedirectUrl;
            }else{
                return "It is failed to connect to: " + m_objOriginalUrl;
            }
        }
    }
	public static void main(String[] args){
		try{
		    URL url = URLUtil.getURL("http://www.blackbeltmag.com/adsystem/redir.cfm?adid=66");
		    /*URL url = URLUtil.getURL("http://localhost:8888/a.asp");*/
//		    URL url = URLUtil.getURL("http://adfarm.mediaplex.com/ad/ck/706-4314-8174-2?&loc=http://search-desc.ebay.ca/search/search.dll?%26st%3D2%26newu%3D1%26sacategory%3D293%26currdisp%3D1%26query%3Daviation&query=aviation");
		    HrefParser obj = new HrefParser(url, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
		    obj.connect();
		    //System.out.println(obj);
		    System.out.println(obj.getRedirectURL().toExternalForm());
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	
	//++changsheng 2006-7-24
	public String getFileType()
	{
	    String sExt = m_objRedirectUrl.getPath();
        if(sExt == null || sExt.length() < 5){
            return ".xxx";
        }
        String sRight4 = sExt.substring(sExt.length() - 5).toLowerCase();
        String sRight3 = sRight4.substring(1);
        if(sRight4.charAt(0) == '.' || sRight3.charAt(0) == '.'){
            return sRight3 ;
        }
        return ".xxx";
	}
	//--
}
